'use strict';

const Controller = require('egg').Controller;

const { getCookieValue } = require('../public/processCookies');
/**
* @controller OnuController 注释必写，swagger-doc是根据这段注释来生成接口的 ）。
*/
class OnuController extends Controller {
  async getOnuNums() {
    /**
        * @summary getOnuNums
        * @description getOnuNums
        * @router get /getOnuNums
       */
    const params = this.ctx.query;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    const result = await this.ctx.service.onu.getOnuNums(params);
    this.ctx.body = {
      msg: '',
      status: 200,
      count: result.count,
    };
  }
  async list() {
    /**
        * @summary onulist
        * @description onulist
        * @router get /onulist
        * @request query integer limit
        * @request query integer page
        * @request query String OltId
        * @request query String search
        * @request query String state
        * @request query String PONindex
        */
    const params = this.ctx.query;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    const result = await this.ctx.service.onu.list(params);
    this.ctx.body = {
      msg: '',
      status: 200,
      data: result.rows,
      count: result.count,
    };
  }
  async refresh() {
    /**
        * @summary onurefresh
        * @description onurefresh
        * @router get /onurefresh
        * @request query String oltId
        */
    const params = this.ctx.query;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    let oltstate;
    if(params.oltId == 'Any'){
      const result = await this.ctx.model.Olt.find({tid:params.tid})
      for(var i=0;i<result.length;i++){
        try {
          oltstate = await this.ctx.service.olt.getOltStatus({OltId:result[i]._id})
          if(oltstate.flag == true){
            await this.ctx.service.olt.getRegisteredONUList({OltId:result[i]._id,tid:params.tid})
          }
        } catch (error) {
          console.log(error)
        }
      }
    }else{
      try {
        oltstate = await this.ctx.service.olt.getOltStatus({OltId:params.oltId})
        if(oltstate.flag == true){
          await this.ctx.service.olt.getRegisteredONUList({OltId:params.oltId,tid:params.tid})
        }
      } catch (error) {
        console.log(error)
        return this.ctx.body = {
          flag:false,
          msg:JSON.stringify(error),
          status:200
        }
      }
    }
    if(params.oltId == 'Any'){
      this.ctx.body = {
        flag:true,
        status:200
      }
    }else{
      if(oltstate.flag == true){
        this.ctx.body = {
          flag:true,
          status:200
        }
      }else{
        this.ctx.body = {
          flag:false,
          status:200
        }
      }
    }
    // params.tid = tid;
    // const result = await this.ctx.service.onu.refresh(params);
    // if (params.oltId == '') {
    //   global.log.desc = 'All olts onu refresh';
    // } else {
    //   const oltResult = await this.ctx.model.Olt.findOne({ where: { id: params.oltId } });
    //   global.log.desc = `${oltResult.name} ${oltResult.oltIP} onu refresh`;
    // }
    // this.ctx.body = {
    //   msg: result,
    // };
    
  }
  async delete() {
    /**
        * @summary onudelete
        * @description onudelete
        * @router get /onudelete
        * @request query String id
        */
    const params = this.ctx.query;
    const result = await this.ctx.service.onu.delete(params);
    this.ctx.body = {
      msg: result,
    };
  }
  async bind() {
    /**
        * @summary onubind
        * @description onubind
        * @router get /onubind
        * @request query String id
        * @request query String userId
        */
    const params = this.ctx.query;
    const onuResult = await this.ctx.model.Onu.findOne({ where: { id: params.id } });
    const userResult = await this.ctx.model.User.findOne({ where: { id: params.userId } });
    const result = await this.ctx.service.onu.bind(params);
    global.log.desc = `${getCookieValue(this.ctx.cookies, 'token', 'name')} operate ${onuResult.ONUname} bind user ${userResult.name}`;
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async unbind() {
    /**
        * @summary onuunbind
        * @description onuunbind
        * @router get /onuunbind
        * @request query String id
        */
    const params = this.ctx.query;
    const onuResult = await this.ctx.model.Onu.findOne({ where: { id: params.id } });
    const userResult = await this.ctx.model.User.findOne({ where: { id: onuResult.userId } });
    const result = await this.ctx.service.onu.unbind(params);
    global.log.desc = `${getCookieValue(this.ctx.cookies, 'token', 'name')} operate ${onuResult.ONUname} unbind user ${userResult.name}`;
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async onuBindVlan() {
    /**
        * @summary 绑定多vlan
        * @description 绑定多vlan
        * @router post /onuBindVlan
        * @request body onuBindVlan value 传入参数
        */
    const options = this.ctx.request.body;
    const { oltID, vlan, ponIndex, onuIndex, upstream, downstream, lineProfile, srvProfile } = options;
    console.log(oltID, vlan, ponIndex, onuIndex);
    // 1.根据oltID来判断olt的品牌
    const olt = await this.ctx.service.olt.oltsingle({ OltId: oltID });
    let result;
    olt && (result = await this.ctx.service.onu.onuBindVlan(olt, ponIndex, onuIndex, vlan, upstream, downstream, lineProfile, srvProfile));
    console.log('绑定多条vlan返回：', result);
    if (result) {
      this.ctx.status = 200;
      this.ctx.body = {
        code: 200,
        msg: 'success',
      };
    } else {
      this.ctx.status = 200;
      this.ctx.body = {
        code: 200,
        msg: 'fail',
      };
    }
  }
  async getONUDetails() {
    /**
    * @summary 通过omci获取onu的detail信息
    * @description 通过omci获取onu的detail信息
    * @router get /getONUDetails
    * @request query String id
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.onu.getONUDetails(params);
    this.ctx.body = {
      msg: result,
    };
  }
  async onuManagement(){
    const {type,id} = this.ctx.query;
    const result = await this.ctx.service.onu.onuManagement(type,id);
    console.log(type,id,result);
    this.ctx.body = {
      msg:"success"
    }
  }
  async setCatvState(){
     /**
        * @summary setCatvState
        * @description setCatvState
        * @router get /setcatvstate
        * @request query String OltId
        * @request query String id
        * @request query String catvstate
        */
    const params = this.ctx.query;
    const result = await this.ctx.service.onu.setCatvState(params)
    this.ctx.body = {
      flag:result.flag,
      msg:result.msg
    }
  }

  //todo 获取onu的能力集
  async getONUCapability(){
    this.ctx.body = {
      msg:"",
      status:200
    }
  }

  //todo 查询onu的voip状态
  async getOnuVoip(){
    this.ctx.body = {
      msg:"",
      status:200
    }
  }
  //TODO 设置onu的voip信息
  async setOnuVoip(){
    this.ctx.body = {
      msg:"",
      status:200
    }
  }
}



module.exports = OnuController;
